class SucursalesController < ApplicationController
  #MODULE: Configuraciones
  #ACTIONS: scaffold

  include Jqgrid
  # GET /sucursales
  # GET /sucursales.xml
  def index
    respond_to do |format|
      format.html # show.html.erb
      format.combo  { render :file => "sucursales/index.combo.erb" }
    end
  end

  # GET /sucursales/1
  # GET /sucursales/1.xml
  def show
    @sucursal = Sucursal.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @sucursal }
    end
  end

  # GET /sucursales/new
  # GET /sucursales/new.xml
  def new
    @sucursal = Sucursal.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @sucursal }
    end
  end

  # GET /sucursales/1/edit
  def edit
    @sucursal = Sucursal.find(params[:id])
  end

  # POST /sucursales
  # POST /sucursales.xml
  def create
    @sucursal = Sucursal.new(params[:sucursal])

    respond_to do |format|
      if @sucursal.save
        flash[:notice] =  'Sucursal creada correctamente.'
        format.html { params[:oper].nil? ? redirect_to(@sucursal) : render(:text => "Ok")}
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @sucursal.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /sucursales/1
  # PUT /sucursales/1.xml
  def update
    @sucursal = Sucursal.find(params[:id])

    respond_to do |format|
      if @sucursal.update_attributes(params[:sucursal])
        flash[:notice] = 'Sucursal actualizado correctamente.'
        format.html { redirect_to(@sucursal) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @sucursal.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /sucursales/1
  # DELETE /sucursales/1.xml
  def destroy
    @sucursal = Sucursal.find(params[:id])
    @sucursal.deleted_at=Time.now
    @sucursal.save

    respond_to do |format|
      format.html { redirect_to(sucursales_url) }
      format.xml  { head :ok }
    end
  end

  def datos #IGNORE
    registros,count = find_by_params(params, :class => Sucursal)

    # Construct a hash from the ActiveRecord result
    return_data = Hash.new()
    return_data[:page] = params[:page]
    return_data[:total] = (count.to_f / params[:rows].to_i).ceil
    return_data[:records] = count

    return_data[:rows] = registros.collect{|u| {:id=>u.id,
        :cell=>[
          u.nombre,u.empresa.try(:nombre)
        ]}}

    # Convert the hash to a json object
    render :text=>return_data.to_json, :layout=>false
  end

end
